'use client';

import { getMaskUrl } from '@/lib/api';

import { useState, useEffect, useCallback, useRef } from "react";

export default function TaskResultDisplay({ result, taskId, imageUrl, onShowMask }) {
  if (!result) return null;

  // 为检测任务管理mask设置状态
  const [maskSettings, setMaskSettings] = useState({});
  const [currentActiveMask, setCurrentActiveMask] = useState(null); // 跟踪当前激活的mask
  const debounceTimerRef = useRef(null);

  // 防抖的mask更新函数
  const debouncedUpdateMask = useCallback((maskUrl, opacity, colorMap) => {
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    debounceTimerRef.current = setTimeout(() => {
      if (opacity > 0) {
        onShowMask(imageUrl, maskUrl, opacity, colorMap);
        setCurrentActiveMask(maskUrl);
      } else {
        onShowMask(imageUrl, null);
        setCurrentActiveMask(null);
      }
    }, 300); // 300ms 防抖延迟
  }, [imageUrl, onShowMask]);

  // 当检测或分割结果首次加载时，初始化mask设置
  useEffect(() => {
    // 处理检测任务
    if (taskId === 'detection' && result?.results?.detections) {
      console.log('TaskResultDisplay - 检测到检测结果，初始化 mask 设置');
      const initialSettings = {};
      let firstMaskUrl = null;

      result.results.detections.forEach(detection => {
        const maskId = detection.mask;
        initialSettings[maskId] = {
          opacity: 0.7,
          colorMap: 'red'
        };
        // 使用第一个检测的 mask 设置显示参数
        if (!firstMaskUrl) {
          firstMaskUrl = getMaskUrl(detection.mask);
        }
      });

      setMaskSettings(initialSettings);
      // 显示第一个检测结果的 mask
      if (firstMaskUrl) {
        onShowMask(imageUrl, firstMaskUrl, 0.7, 'red');
        setCurrentActiveMask(firstMaskUrl);
      }
      console.log('TaskResultDisplay - 初始化设置:', initialSettings);
    }
  }, [taskId, result, imageUrl]);

  // 清理防抖定时器
  useEffect(() => {
    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
    };
  }, []);

  // 更新mask设置
  const updateMaskSetting = (maskId, setting, value) => {
    setMaskSettings(prev => ({
      ...prev,
      [maskId]: {
        ...prev[maskId],
        [setting]: value
      }
    }));
  };

  // 添加调试日志
  console.log("TaskResultDisplay - taskId:", taskId);
  console.log("TaskResultDisplay - result:", result);
  console.log("TaskResultDisplay - maskSettings:", maskSettings);

  /* 下面的所有render的具体变量名需要和后端传入的保持一致 */
  const renderDetectionResults = () => {
    if (!result.results.detections || !Array.isArray(result.results.detections)) return null;

    const handleHideAll = () => {
      // 清除防抖定时器
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }

      // 将所有mask的透明度设置为0来隐藏
      const updatedSettings = {};
      result.results.detections.forEach(detection => {
        const maskId = detection.mask;
        updatedSettings[maskId] = {
          ...maskSettings[maskId],
          opacity: 0
        };
      });
      setMaskSettings(prev => ({ ...prev, ...updatedSettings }));
      onShowMask(imageUrl, null);
      setCurrentActiveMask(null);
    };

    // 计算当前显示的mask数量（透明度>0的mask）
    const visibleCount = result.results.detections.reduce((count, detection) => {
      const maskId = detection.mask;
      const settings = maskSettings[maskId];
      return count + (settings && settings.opacity > 0 ? 1 : 0);
    }, 0);

    return (
      <div>
        <div className="flex justify-between items-center mb-2">
          <h4 className="font-medium text-gray-900">检测结果</h4>
          <div className="flex gap-2">
            <span className="text-xs text-gray-500">
              显示: {visibleCount} / {result.results.detections.length}
            </span>
            {visibleCount > 0 && (
              <button
                onClick={handleHideAll}
                className="px-2 py-1 bg-gray-500 text-white text-xs rounded hover:bg-gray-600"
              >
                隐藏所有
              </button>
            )}
          </div>
        </div>
        <div className="space-y-3">
          {result.results.detections.map((detection, index) => {
            const maskUrl = getMaskUrl(detection.mask);
            const maskId = detection.mask;
            const settings = maskSettings[maskId] || { opacity: 0.7, colorMap: 'red' };

            return (
              <div key={index} className="p-3 bg-yellow-50 border border-yellow-200 rounded">
                <div className="space-y-2">
                  <div className="text-xs text-gray-600 break-all">
                    <span className="font-medium">Mask URL:</span> {maskUrl}
                  </div>
                  <div className="flex justify-between items-center">
                    <div className="text-xs text-blue-600">
                      <span className="font-medium">状态:</span>
                      <span className={`ml-1 px-2 py-1 rounded text-xs ${settings.opacity > 0
                        ? 'bg-green-100 text-green-800'
                        : 'bg-gray-100 text-gray-600'
                        }`}>
                        {settings.opacity > 0 ? '已显示' : '已隐藏'}
                      </span>
                      {currentActiveMask === maskUrl && settings.opacity > 0 && (
                        <span className="ml-1 px-2 py-1 rounded text-xs bg-blue-100 text-blue-800">
                          当前激活
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="text-xs font-medium text-gray-700">透明度:</label>
                      <input
                        type="range"
                        min="0"
                        max="1"
                        step="0.1"
                        value={settings.opacity}
                        onChange={(e) => {
                          const newOpacity = parseFloat(e.target.value);
                          updateMaskSetting(maskId, 'opacity', newOpacity);

                          // 如果设置透明度大于0，先将其他mask设置为0（确保只有一个mask激活）
                          if (newOpacity > 0) {
                            const updatedSettings = {};
                            result.results.detections.forEach(detection => {
                              const otherMaskId = detection.mask;
                              if (otherMaskId !== maskId) {
                                updatedSettings[otherMaskId] = {
                                  ...maskSettings[otherMaskId],
                                  opacity: 0
                                };
                              }
                            });
                            if (Object.keys(updatedSettings).length > 0) {
                              setMaskSettings(prev => ({ ...prev, ...updatedSettings }));
                            }
                          }

                          // 使用防抖函数更新 mask
                          debouncedUpdateMask(maskUrl, newOpacity, settings.colorMap);
                        }}
                        className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                      />
                      <span className="text-xs text-gray-500">{settings.opacity}</span>
                    </div>
                    <div>
                      <label className="text-xs font-medium text-gray-700">颜色:</label>
                      <select
                        value={settings.colorMap}
                        onChange={(e) => {
                          const newColor = e.target.value;
                          updateMaskSetting(maskId, 'colorMap', newColor);
                          // 当颜色改变且透明度>0时，立即更新 mask（颜色改变不需要防抖）
                          if (settings.opacity > 0) {
                            // 取消之前的防抖定时器，立即应用颜色变化
                            if (debounceTimerRef.current) {
                              clearTimeout(debounceTimerRef.current);
                            }
                            onShowMask(imageUrl, maskUrl, settings.opacity, newColor);
                            setCurrentActiveMask(maskUrl);
                          }
                        }}
                        className="w-full px-2 py-1 text-xs border border-gray-300 rounded"
                      >
                        <option value="red">红色</option>
                        <option value="green">绿色</option>
                        <option value="blue">蓝色</option>
                      </select>
                    </div>
                    <div className="col-span-2 flex justify-end">
                      <button
                        onClick={() => {
                          // 快速激活这个mask（设置为0.7透明度，其他设为0）
                          const updatedSettings = {};
                          result.results.detections.forEach(detection => {
                            const otherMaskId = detection.mask;
                            updatedSettings[otherMaskId] = {
                              ...maskSettings[otherMaskId],
                              opacity: otherMaskId === maskId ? 0.7 : 0
                            };
                          });
                          setMaskSettings(prev => ({ ...prev, ...updatedSettings }));

                          // 立即显示这个mask
                          if (debounceTimerRef.current) {
                            clearTimeout(debounceTimerRef.current);
                          }
                          onShowMask(imageUrl, maskUrl, 0.7, settings.colorMap);
                          setCurrentActiveMask(maskUrl);
                        }}
                        className="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600"
                        disabled={settings.opacity > 0}
                      >
                        {settings.opacity > 0 ? '已激活' : '快速显示'}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  // 动态渲染分类结果
  const renderClassificationResults = () => {
    console.log("TaskResultDisplay", result);
    const list = result.results.classifications;
    if (!list || list.length === 0) return null;

    return (
      <div>
        <h4 className="font-medium text-gray-900 mb-2">分类结果</h4>
        <div className="space-y-3">
          {list.map((item, idx) => (
            <div key={idx} className="p-3 bg-blue-50 border border-blue-200 rounded">
              <div className="space-y-2">
                {/* 自动渲染 item 里所有键值对 */}
                {Object.entries(item).map(([key, value]) => (
                  <div className="flex justify-between" key={key}>
                    <span className="font-medium text-blue-900">
                      {key.replace(/_/g, ' ').toUpperCase()}:
                    </span>
                    <span className="text-blue-700">
                      {/* 数字且 0-1 之间 → 百分比 */}
                      {typeof value === 'number' && value >= 0 && value <= 1
                        ? `${(value * 100).toFixed(2)}%`
                        : String(value)}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  // 动态渲染分级结果
  const renderGradingResults = () => {
    console.log("TaskResultDisplay", result);
    const list = result.results.gradings;
    if (!list || list.length === 0) return null;

    return (
      <div>
        <h4 className="font-medium text-gray-900 mb-2">分级结果</h4>
        <div className="space-y-3">
          {list.map((item, idx) => (
            <div key={idx} className="p-3 bg-blue-50 border border-blue-200 rounded">
              <div className="space-y-2">
                {/* 自动渲染 item 里所有键值对 */}
                {Object.entries(item).map(([key, value]) => (
                  <div className="flex justify-between" key={key}>
                    <span className="font-medium text-blue-900">
                      {key.replace(/_/g, ' ').toUpperCase()}:
                    </span>
                    <span className="text-blue-700">
                      {/* 数字且 0-1 之间 → 百分比 */}
                      {typeof value === 'number' && value >= 0 && value <= 1
                        ? `${(value * 100).toFixed(2)}%`
                        : String(value)}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };
  // 动态渲染分期结果
  const renderStagingResults = () => {
    console.log("TaskResultDisplay", result);
    const list = result.results.stagings;
    if (!list || list.length === 0) return null;

    return (
      <div>
        <h4 className="font-medium text-gray-900 mb-2">分级结果</h4>
        <div className="space-y-3">
          {list.map((item, idx) => (
            <div key={idx} className="p-3 bg-blue-50 border border-blue-200 rounded">
              <div className="space-y-2">
                {/* 自动渲染 item 里所有键值对 */}
                {Object.entries(item).map(([key, value]) => (
                  <div className="flex justify-between" key={key}>
                    <span className="font-medium text-blue-900">
                      {key.replace(/_/g, ' ').toUpperCase()}:
                    </span>
                    <span className="text-blue-700">
                      {/* 数字且 0-1 之间 → 百分比 */}
                      {typeof value === 'number' && value >= 0 && value <= 1
                        ? `${(value * 100).toFixed(2)}%`
                        : String(value)}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  const renderSegmentationResults = () => {
    if (!result.results.segmentations || !Array.isArray(result.results.segmentations)) return null;

    // 为分割任务维护简单的显示状态
    // 为分割任务管理mask设置状态，与检测任务保持一致
    const [maskSettings, setMaskSettings] = useState({});
    const [currentActiveMask, setCurrentActiveMask] = useState(null);

    // 初始化分割结果的mask设置
    useEffect(() => {
      // 处理分割任务
      if (taskId === 'segmentation' && result?.results?.segmentations) {
        console.log('TaskResultDisplay - 检测到分割结果，初始化 mask 设置');
        const initialSettings = {};
        let firstMaskUrl = null;
  
        result.results.segmentations.forEach(segmentation => {
          const maskId = segmentation.lesion_id || segmentation.mask;
          initialSettings[maskId] = {
            opacity: 0.7,
            colorMap: 'red'
          };
          // 使用第一个分割的 mask 设置显示参数
          if (!firstMaskUrl) {
            firstMaskUrl = getMaskUrl(segmentation.mask);
          }
        });
  
        setMaskSettings(initialSettings);
        // 显示第一个分割结果的 mask
        if (firstMaskUrl) {
          onShowMask(imageUrl, firstMaskUrl, 0.7, 'red');
          setCurrentActiveMask(firstMaskUrl);
        }
        console.log('TaskResultDisplay - 分割结果初始化设置:', initialSettings);
      }
    }, [taskId, result, imageUrl]);

    // 重用检测任务的防抖更新函数
    const updateMaskSetting = (maskId, setting, value) => {
      setMaskSettings(prev => ({
        ...prev,
        [maskId]: {
          ...prev[maskId],
          [setting]: value
        }
      }));
    };

    const handleHideAll = () => {
      // 清除防抖定时器
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
  
      // 将所有mask的透明度设置为0来隐藏
      const updatedSettings = {};
      result.results.segmentations.forEach(segmentation => {
        const maskId = segmentation.lesion_id || segmentation.mask;
        updatedSettings[maskId] = {
          ...maskSettings[maskId],
          opacity: 0
        };
      });
      setMaskSettings(prev => ({ ...prev, ...updatedSettings }));
      onShowMask(imageUrl, null);
      setCurrentActiveMask(null);
    };

    // 计算当前显示的mask数量（透明度>0的mask）
    const visibleCount = result.results.segmentations.reduce((count, segmentation) => {
      const maskId = segmentation.lesion_id || segmentation.mask;
      const settings = maskSettings[maskId];
      return count + (settings && settings.opacity > 0 ? 1 : 0);
    }, 0);

    return (
      <div>
        <div className="flex justify-between items-center mb-2">
          <h4 className="font-medium text-gray-900">分割结果</h4>
          <div className="flex gap-2">
            <span className="text-xs text-gray-500">
              显示: {visibleCount} / {result.results.segmentations.length}
            </span>
            {visibleCount > 0 && (
              <button
                onClick={handleHideAll}
                className="px-2 py-1 bg-gray-500 text-white text-xs rounded hover:bg-gray-600"
              >
                隐藏所有
              </button>
            )}
          </div>
        </div>
        <div className="space-y-3">
          {result.results.segmentations.map((segmentation, index) => {
            const maskUrl = getMaskUrl(segmentation.mask);
            const maskId = segmentation.lesion_id || segmentation.mask;
            const settings = maskSettings[maskId] || { opacity: 0.7, colorMap: 'red' };

            return (
              <div key={index} className="p-3 bg-green-50 border border-green-200 rounded">
                <div className="space-y-2">
                  <div className="text-xs text-gray-600 break-all">
                    <span className="font-medium">Mask URL:</span> {maskUrl}
                  </div>
                  <div className="flex justify-between items-center">
                    <div className="text-xs text-blue-600">
                      <span className="font-medium">状态:</span>
                      <span className={`ml-1 px-2 py-1 rounded text-xs ${settings.opacity > 0
                        ? 'bg-green-100 text-green-800'
                        : 'bg-gray-100 text-gray-600'
                        }`}>
                      {settings.opacity > 0 ? '已显示' : '已隐藏'}
                      </span>
                      {currentActiveMask === maskUrl && settings.opacity > 0 && (
                        <span className="ml-1 px-2 py-1 rounded text-xs bg-blue-100 text-blue-800">
                          当前激活
                        </span>
                      )}
                    </div>
                    {/* <div className="text-xs text-gray-500">
                      ID: {maskId}
                    </div> */}
                  </div>
                  {onShowMask && imageUrl && (
                    <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="text-xs font-medium text-gray-700">透明度:</label>
                          <input
                            type="range"
                            min="0"
                            max="1"
                            step="0.1"
                            value={settings.opacity}
                            onChange={(e) => {
                              const newOpacity = parseFloat(e.target.value);
                              updateMaskSetting(maskId, 'opacity', newOpacity);
                    
                              // 如果设置透明度大于0，先将其他mask设置为0（确保只有一个mask激活）
                              if (newOpacity > 0) {
                                const updatedSettings = {};
                                result.results.segmentations.forEach(seg => {
                                  const otherMaskId = seg.lesion_id || seg.mask;
                                  if (otherMaskId !== maskId) {
                                    updatedSettings[otherMaskId] = {
                                      ...maskSettings[otherMaskId],
                                      opacity: 0
                                    };
                                  }
                                });
                                if (Object.keys(updatedSettings).length > 0) {
                                  setMaskSettings(prev => ({ ...prev, ...updatedSettings }));
                                }
                              }
                    
                              // 使用防抖函数更新 mask
                              debouncedUpdateMask(maskUrl, newOpacity, settings.colorMap);
                            }}
                            className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                          />
                          <span className="text-xs text-gray-500">{settings.opacity}</span>
                        </div>
                        <div>
                          <label className="text-xs font-medium text-gray-700">颜色:</label>
                          <select
                            value={settings.colorMap}
                            onChange={(e) => {
                              const newColor = e.target.value;
                              updateMaskSetting(maskId, 'colorMap', newColor);
                              // 当颜色改变且透明度>0时，立即更新 mask（颜色改变不需要防抖）
                              if (settings.opacity > 0) {
                                // 取消之前的防抖定时器，立即应用颜色变化
                                if (debounceTimerRef.current) {
                                  clearTimeout(debounceTimerRef.current);
                                }
                                onShowMask(imageUrl, maskUrl, settings.opacity, newColor);
                                setCurrentActiveMask(maskUrl);
                              }
                            }}
                            className="w-full px-2 py-1 text-xs border border-gray-300 rounded"
                          >
                            <option value="red">红色</option>
                            <option value="green">绿色</option>
                            <option value="blue">蓝色</option>
                          </select>
                        </div>
                        <div className="flex gap-2 mt-2">
                          <button
                            onClick={() => {
                              // 快速激活这个mask（设置为0.7透明度，其他设为0）
                              const updatedSettings = {};
                              result.results.segmentations.forEach(seg => {
                                const otherMaskId = seg.lesion_id || seg.mask;
                                updatedSettings[otherMaskId] = {
                                  ...maskSettings[otherMaskId],
                                  opacity: otherMaskId === maskId ? 0.7 : 0
                                };
                              });
                              setMaskSettings(prev => ({ ...prev, ...updatedSettings }));
                    
                              // 立即显示这个mask
                              if (debounceTimerRef.current) {
                                clearTimeout(debounceTimerRef.current);
                              }
                              onShowMask(imageUrl, maskUrl, 0.7, settings.colorMap);
                              setCurrentActiveMask(maskUrl);
                            }}
                            className="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600"
                            disabled={settings.opacity > 0}
                          >
                            {settings.opacity > 0 ? '已激活' : '快速显示'}
                          </button>
                        </div>
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  const renderRegressionResults = () => {
    if (!result.results.regression) return null;

    return (
      <div>
        <h4 className="font-medium text-gray-900 mb-2">she结果</h4>
        <div className="p-3 bg-purple-50 border border-purple-200 rounded">
          <span className="text-purple-900">{result.results.regression}</span>
        </div>
      </div>
    );
  };

  return (
    <div className="bg-white p-6 rounded-lg border border-gray-200">
      {/* 添加调试信息显示
      <div className="mb-2 p-2 bg-yellow-50 border border-yellow-200 rounded text-xs">
        <p>当前taskId: {taskId}</p>
        <p>条件匹配: {taskId === 'detection' ? '是' : '否'}</p>
        <p>有检测结果: {result.results.detections && result.results.detections.length > 0 ? '是' : '否'}</p>
      </div> */}

      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-gray-900">分析结果</h3>
        <span className="px-3 py-1 bg-green-100 text-green-800 text-sm rounded-full">
          处理完成
        </span>
      </div>

      <div className="space-y-6">
        {/* 尝试直接调用渲染函数，不做条件判断 */}
        {/* {renderDetectionResults()} */}

        {/* 原有的条件渲染逻辑, 需要附加层级关系，任务间不是并行的 */}
        {taskId === 'detection' && renderDetectionResults()}
        {taskId === 'classification' && renderClassificationResults()}
        {taskId === 'segmentation' && renderSegmentationResults()}
        {taskId === 'regression' && renderRegressionResults()}
        {taskId === 'grading' && renderGradingResults()}
        {taskId === 'staging' && renderStagingResults()}

      </div>

      <div className="mt-6 pt-4 border-t border-gray-200">
        <div className="flex space-x-4">
          <button className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 text-sm">
            导出结果
          </button>
          {/* <button className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 text-sm">
            保存报告
          </button> */}
        </div>
      </div>
    </div>
  );
}